﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Checkpoint2XNA.Models;
using Microsoft.Xna.Framework;

namespace Checkpoint2XNA.Utilities
{
    public abstract class QuadTree
    {
        public static Model3D[] grid;

        public static QuadTreeNode Root { get; set; }

        public static void ConstructTree(Vector3 boardPos, float checkerSize, float height)
        {
            QuadTreeNode[] leaves = new QuadTreeNode[64];
            for (int i = 0; i < 64; i++)
            {
                leaves[i] = new QuadTreeNode(new BoxStruct { Min = new Vector3(boardPos.X + (i % 8) * checkerSize, boardPos.Y, boardPos.Z + (i / 8) * checkerSize), 
                                                             Max = new Vector3(boardPos.X + (i % 8) * checkerSize + checkerSize, boardPos.Y + height, boardPos.Z + (i / 8) * checkerSize + checkerSize) }, i);
            }

            QuadTreeNode[] second = new QuadTreeNode[16];
            for (int i = 0; i < 16; i++)
            {
                var baseIndex = (i % 4) * 2 + (i / 4) * 16;
                second[i] = new QuadTreeNode(leaves[baseIndex], leaves[baseIndex + 1], leaves[baseIndex + 8], leaves[baseIndex + 9]);
            }

            QuadTreeNode[] third = new QuadTreeNode[4];
            for (int i = 0; i < 4; i++)
            {
                var baseIndex = (i % 4) * 2 + (i / 4) * 16;
                third[i] = new QuadTreeNode(second[baseIndex], second[baseIndex + 1], second[baseIndex + 8], second[baseIndex + 9]);
            }

            Root = new QuadTreeNode(third);
        }

        public static Tuple<Model3D, double> RayCollide(Vector3 origin, Vector3 ray)
        {
            Vector3 invRay = new Vector3(1.0f / ray.X, 1.0f / ray.Y, 1.0f / ray.Z);
            return Root.RayCollide(origin, ray, invRay);
        }
    }
}
